<template>
    <div>
      <template v-if="isSameUser(msgIndex)">
          <div class="msg text-break repeat-msg" @contextmenu.prevent="sendToContextMenu">
            <span class="repeat-msg-date">{{ toDateTime(msgInfo.send_time) }}</span>
            <span v-if="!isEditing" :class="{'text-secondary-emphasis': msgInfo.isOnSending}">{{ msgInfo.text }}<span v-if="msgInfo.edited_at" style="font-size: 12px" class="text-secondary">(已编辑)</span></span>
            <div v-if="isEditing">
              <div
                  class="p-2 bg-body rounded-3 editingDiv"
                  ref="editingMsgRef"
                  :contenteditable="isEditing"
                  @keydown.enter.prevent="editedSubmit"
                  @keydown.esc.prevent="isEditing=!isEditing"
              >
                {{ msgInfo.text }}
              </div>
              <p style="font-size: 12px"><b>ESC</b> <span class="text-primary-emphasis">取消编辑</span> • <b>回车</b> <span class="text-primary-emphasis">保存</span></p>
            </div>

            <Attachment
                :progress="msgInfo.progress"
                :file="msgInfo.file"
                :is-sending="msgInfo.isOnSending"
                :AttachmentUrlGroupConcat="msgInfo.filenames"
                :AttachmentMimeTypeGroupConcat="msgInfo.mimeType"
            />
          </div>
      </template>

      <template v-else>
        <div class="time-divider" v-show="showTimestamp(msgIndex)">
          <hr class="w-100 border-secondary"/><span class="date">{{ toNormalTime(msgInfo.send_time) }}</span><hr class="w-100"/>
        </div>

        <div :class="['msgStart', {'m-0': showTimestamp(msgIndex)}]" class="position-relative"  @contextmenu.prevent="sendToContextMenu">
            <img class="user-avatar" @click.prevent="showMiniProfileCard(msgInfo.sender_id, $event)" :src="host_custom+'/pfp/'+msgInfo.avatar" alt="user_avatar">

            <div class="flex-msg">
              <div>
                <span class="username"><a class="text-decoration-none" :href="`http://localhost:5173/checkUserProfile/${msgInfo.sender_id}`">{{ msgInfo.name }}</a></span>
                <span class="date" style="padding-left: 6px;">{{ toNormalDateTime(msgInfo.send_time) }}</span>
              </div>
              <div class="m-0 text-break">
                <span v-if="!isEditing" :class="{ 'text-secondary-emphasis': msgInfo.isOnSending}">{{ msgInfo.text }} <span v-if="msgInfo.edited_at" style="font-size: 12px" class="text-secondary">(已编辑)</span></span>
                <div v-if="isEditing">
                  <div
                      class="p-2 bg-body rounded-3 editingDiv"
                      ref="editingMsgRef"
                      :contenteditable="isEditing"
                      @keydown.enter.prevent="editedSubmit"
                      @keydown.esc.prevent="isEditing=!isEditing"
                  >
                    {{ msgInfo.text }}
                  </div>
                  <p style="font-size: 12px"><b>ESC</b> <span class="text-primary-emphasis">取消编辑</span> • <b>回车</b> <span class="text-primary-emphasis">保存</span></p>
                </div>

                <Attachment
                  :progress="msgInfo.progress"
                  :file="msgInfo.file"
                  :is-sending="msgInfo.isOnSending"
                  :AttachmentUrlGroupConcat="msgInfo.filenames"
                  :AttachmentMimeTypeGroupConcat="msgInfo.mimeType"
                />
              </div>
            </div>
          </div>
      </template>
    </div>
</template>

<script setup>
import 'animate.css'
import {host_custom} from "@/host.js";
import {defineProps, onMounted, reactive, onBeforeMount, ref, nextTick} from "vue";
import Attachment from "@/pages/chat/components/Attachment.vue";
import {messageService} from "@/service/messageService.js";
import emitter from "@/utils/EventBus.js";
const voiceUrl = reactive({})
const props = defineProps({
  chat_data: Array,
  msgIndex: Number,
  msgInfo: Object,
  chatId: String,
});


const editingMsgRef = ref()
const isEditing = ref(false)

// const editedContent = ref('')
const editedSubmit = async () => {
  if (editingMsgRef.value.innerText === props.msgInfo.text) {
    isEditing.value = false
    return void 0
  }
  console.warn('editing '+ props.msgInfo.id)
  const res = await messageService().updateEditedMsg({msgId: props.msgInfo.id, content: editingMsgRef.value.innerText, chatId: props.chatId})
  if (res) {
    isEditing.value = false
    msgInfo.text = editingMsgRef.value.innerText
    msgInfo.edited_at = '1'
    return void 0
  }
}
const ex_fun = async () => {
  isEditing.value = true
  await nextTick(() => editingMsgRef.value.focus())
}

defineExpose({
  ex_fun
})

const chat_data = props.chat_data
const msgIndex = props.msgIndex
const msgInfo = props.msgInfo

const emit  = defineEmits(['onContextMenu'])

const showMiniProfileCard = (id, event) => {
  emitter.emit('showMiniProfileCard', {
    uid: id,
    boundingClientRect: event.target.getBoundingClientRect(),
  })
}

const sendToContextMenu = (e) => {
  emit('onContextMenu', {msgInfo: props.msgInfo, msgIndex, mousePosition: {x: e.clientX, y: e.clientY}})
};


const theViewportEdgeBottom = ref(0)
onMounted(()=> {
  theViewportEdgeBottom.value = document.querySelector('.msg_wrapper').getBoundingClientRect().bottom
})

onBeforeMount(async () => {
    // if (!msgInfo.msg) {
    //   const msgId = msgInfo.id
    //   const blob = await axios.get(host_custom+'/getVoiceById', {responseType: "blob",params: {msgId: msgId, roomNumber: props.groupId}})
    //   const webmUrl = URL.createObjectURL(blob.data)
    //   let indexName = msgId.toString()
    //   voiceUrl[indexName] = webmUrl;
    // }
})

const isSameUser = (index) => {
  if (chat_data.length === 0) return false
  if (index === 0) return false
  const nextMsgTime = new Date(chat_data[index].send_time).getTime()/1000
  const preMsgTime = new Date(chat_data[index-1].send_time).getTime()/1000
  if(nextMsgTime - preMsgTime > 120) return false
  const nextUser = chat_data[index].sender_id
  const preUser = chat_data[index-1].sender_id
  return preUser === nextUser
}

const showTimestamp = (index) => {
  if (index === 0) return true
  const prevMessage = chat_data[index - 1];
  const prevTimestamp = new Date(prevMessage.send_time).getDate()
  const currTimestamp = new Date(chat_data[index].send_time).getDate()
  return !(prevTimestamp === currTimestamp);
};

const formatNumber = (n) => n < 10 ? '0' + n : n;
const toNormalDateTime =(time) => {
  const date = new Date(time)
  const today = new Date(Date.now())
  if ( today.getFullYear()+today.getMonth()+1+today.getDate() === date.getFullYear()+date.getMonth()+1+date.getDate()) {
    return '今天'+' '+formatNumber(date.getHours()+1)+':'+formatNumber(date.getMinutes())
  } else if(today.getDate() - date.getDate() === 1 && today.getFullYear() === date.getFullYear() && today.getMonth() === date.getMonth()) {
    return '昨天'+' '+formatNumber(date.getHours()+1)+':'+formatNumber(date.getMinutes())
  }  else {
    return date.getFullYear()+'/'+formatNumber(date.getMonth()+1)+'/'+formatNumber(date.getDate())+' '+formatNumber(date.getHours()+1)+':'+formatNumber(date.getMinutes())
  }
}

const toDateTime =(time) => {
  const date = new Date(time)
    return formatNumber(date.getHours()+1)+':'+formatNumber(date.getMinutes())
}

const toNormalTime = (time) => {
  const date = new Date(time)
  return date.getFullYear()+'/'+formatNumber(date.getMonth()+1)+'/'+formatNumber(date.getDate())
}
</script>

<style scoped>
.editingDiv {
  outline: none;
}

.msgStart {
  transition: none;
  margin-top: 17px;
  width: 100%;
  padding: 2px 16px 2px 72px;
  display: flex;
}


.msgStart:hover {
  background-color: var(--bs-tertiary-bg);
}

.user-avatar {
  display: block;
  position: absolute;
  min-width: 40px;
  min-height: 40px;
  width: 40px;
  height: 40px;
  border-radius: 50%;
  z-index: 1;
  margin-top: 3px;
  left: 16px;
  user-select: none;
  cursor: pointer;
}

.repeat-msg {
  transition: none;
  padding: 2px 16px 2px 72px;
}

.repeat-msg-date {
  position: absolute;
  font-size: 12px;
  left: 16px;
  display: none;
  color: #8BA2AD;
}

.msg:hover .repeat-msg-date {
  display: initial;
}

.time-divider {
  padding: 0 16px;
  display: flex;
  align-items: center;
  margin-top: 17px;
}

.time-divider span {
  font-weight: 600;
  white-space: nowrap;
}

.username {
  cursor: pointer;
  font-size: 1rem;
  font-weight: 500;
  line-height: 1.3rem;
  vertical-align: baseline;
  position: relative;
}

.username a {
  color: inherit;
}

.username:hover {
  text-decoration: underline;
}

.msg {
  transition: none !important;
  font-size: 1rem;
  line-height: 1.35rem;
  vertical-align: baseline;
}
.flex-msg {
  line-height: 1.35rem;
  display: flex;
  justify-content: flex-start;
  flex-direction: column;
  width: 100%;
}
.date {
  font-weight: initial;
  font-size: .75rem;
  color: #8BA2AD;
}

.msg:hover {
  background-color: var(--bs-tertiary-bg);
}

@media (max-width: 768px) {
  .msgStart:hover {
    background-color: initial;
  }

  .msg:hover {
    background-color: initial;
  }
}

</style>